package com.cgc.venus.server.job.jobdetail;

import com.cgc.venus.server.core.utils.StringUtil;
import com.cgc.venus.server.job.Constants;
import com.cgc.venus.server.job.bean.TmpBean;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 统计空间镜像
 */
public class StatsNamespaceImagesJob extends AbstractBaseJob {
    private static Logger logger = LoggerFactory.getLogger(StatsNamespaceImagesJob.class);
    public StatsNamespaceImagesJob() {
    }
    public void execute(JobExecutionContext context)  
        throws JobExecutionException {
        logger.info("统计空间镜像job start...");
        List objs = new ArrayList<Object>();
        String sql="";
        String id="";
        try {
            //查询统计信息
            sql="SELECT ns.kube_name namespace, date_format( t1.creation_time, '%Y-%m-%d' ) time FROM t_namespace ns JOIN ( SELECT rep. NAME rName, pro.`name` pName, rep.creation_time FROM repository rep JOIN project pro ON rep.project_id = pro.project_id ) t1 ON ns.harbor_project_name = t1.pName AND t1.pName NOT IN ( SELECT `name` FROM t_repository_public ) AND t1.pName NOT IN ( SELECT `name` FROM t_repository_app_store )";
            List<TmpBean> qr =getJdbcTemplate().query(sql, new Object[]{}, new BeanPropertyRowMapper<TmpBean>(TmpBean.class));
            if(qr!=null&&qr.size()>0){
                Map<String, List<TmpBean>> map = qr.stream().collect(Collectors.groupingBy(TmpBean::getNamespace));//根据命名空间进行分组查询
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                for(String namespace:map.keySet()){
                    objs = new ArrayList<Object>();
                    List<TmpBean> tbs=map.get(namespace);
                    long today=tbs.stream().filter(ts -> sdf.format(new Date()).equals(ts.getTime())).collect(Collectors.toList()).size();
                    //更新统计值表
                    long Ns_Images_private_count_all= tbs.size();
                    long Ns_Images_private_count_today=today;
                    String Ns_name=namespace;
                    sql="select id from t_job_stats_namespace_images where date_format(create_time,'%Y-%m-%d')=date_format(NOW(),'%Y-%m-%d') and Ns_name='"+Ns_name+"'";
                    List<Map<String, Object>> l=getJdbcTemplate().queryForList(sql);
                    if(l!=null&&l.size()>0){
                        //db update
                        sql = "update t_job_stats_namespace_images set Ns_Images_private_count_all=?,Ns_Images_private_count_today=?,last_update_time=NOW() where id=? and Ns_name=?";
                        id=l.get(0).get("id").toString();
                    }else{
                        //db insert
                        sql = "INSERT INTO t_job_stats_namespace_images(Ns_Images_private_count_all,Ns_Images_private_count_today,id,Ns_name,create_time,last_update_time) VALUES (?,?,?,?,NOW(),NOW())";
                        id = StringUtil.getUUID();
                    }
                    objs.add(Ns_Images_private_count_all);
                    objs.add(Ns_Images_private_count_today);
                    objs.add(id);
                    objs.add(Ns_name);
                    getJdbcTemplate().update(sql, objs.toArray());
                }
            }
        }catch (Exception ex){
            logger.error(ex.getMessage(),ex);
            handleEx("统计空间镜像任务异常,异常信息:"+getErrorInfoFromException(ex), Constants.ALARM_TYPE_JOB_ERROR,Constants.ALARM_STATUS_UN,Constants.ALARM_LEVEL_HIGHEST,Constants.ALARM_NS_ALL);
            throw new JobExecutionException(ex);
        }
    }  
}